package org.eiahe.hr.salary.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.system.service.ISysDeptService;
import org.eiahe.hr.salary.domain.SalaryStructure;
import org.eiahe.hr.salary.domain.bo.SalaryPaymentFileBo;
import org.eiahe.hr.salary.mapper.SalaryStructureMapper;
import org.eiahe.hr.salary.service.IFinanceService;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 财务Service业务层处理
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FinanceServiceImpl implements IFinanceService {

    private final SalaryStructureMapper salaryStructureMapper;
    private final ISysDeptService deptService;

    @Override
    public String generateBankPaymentFile(String yearMonth) {
        try {
            // 获取待发放薪资列表
            List<SalaryPaymentFileBo> payments = getPendingPayments(yearMonth);

            if (payments.isEmpty()) {
                return null;
            }

            // 生成文件名
            String fileName = "bank_payment_" + yearMonth + "_" + System.currentTimeMillis() + ".csv";
            String filePath = "/tmp/" + fileName;

            // 写入CSV文件
            try (FileWriter writer = new FileWriter(filePath)) {
                // 写入表头
                writer.write("员工工号,员工姓名,银行卡号,开户行,实发工资\n");

                // 写入数据
                for (SalaryPaymentFileBo payment : payments) {
                    writer.write(String.format("%s,%s,%s,%s,%.2f\n",
                            payment.getEmployeeNo(),
                            payment.getEmployeeName(),
                            payment.getBankCardNo(),
                            payment.getBankName(),
                            payment.getNetSalary()));
                }
            }

            return filePath;
        } catch (Exception e) {
            // 记录日志
            log.error("生成银行代发文件失败", e);
            return null;
        }
    }

    @Override
    public String generatePayrollVoucher(String yearMonth) {
        try {
            // 获取待发放薪资列表
            List<SalaryPaymentFileBo> payments = getPendingPayments(yearMonth);

            if (payments.isEmpty()) {
                return null;
            }

            // 计算总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (SalaryPaymentFileBo payment : payments) {
                totalAmount = totalAmount.add(payment.getNetSalary());
            }

            // 生成文件名
            String fileName = "payroll_voucher_" + yearMonth + "_" + System.currentTimeMillis() + ".txt";
            String filePath = "/tmp/" + fileName;

            // 写入凭证文件
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write("工资凭证\n");
                writer.write("====================================\n");
                writer.write("发放月份: " + yearMonth + "\n");
                writer.write("发放日期: " + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "\n");
                writer.write("员工人数: " + payments.size() + "\n");
                writer.write("总金额: " + totalAmount + "\n");
                writer.write("====================================\n");
                writer.write("员工工号\t员工姓名\t实发工资\n");

                // 写入员工明细
                for (SalaryPaymentFileBo payment : payments) {
                    writer.write(String.format("%s\t%s\t%.2f\n",
                            payment.getEmployeeNo(),
                            payment.getEmployeeName(),
                            payment.getNetSalary()));
                }
            }

            return filePath;
        } catch (Exception e) {
            // 记录日志
            log.error("生成工资凭证失败", e);
            return null;
        }
    }

    @Override
    public List<SalaryPaymentFileBo> getPendingPayments(String yearMonth) {
        try {
            // 查询指定年月的所有薪资数据
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SalaryStructure> queryWrapper = com.baomidou.mybatisplus.core.toolkit.Wrappers
                    .lambdaQuery();
            queryWrapper.eq(SalaryStructure::getYearMonth, yearMonth);
            queryWrapper.eq(SalaryStructure::getStatus, "0"); // 只查询正常状态的数据

            List<SalaryStructure> salaryList = salaryStructureMapper.selectList(queryWrapper);

            List<SalaryPaymentFileBo> result = new ArrayList<>();
            for (SalaryStructure salary : salaryList) {
                SalaryPaymentFileBo bo = new SalaryPaymentFileBo();
                bo.setEmployeeNo(salary.getEmployeeNo());
                bo.setEmployeeName(salary.getEmployeeName());
                bo.setBankCardNo(salary.getBankCardNo());
                bo.setBankName(salary.getBankName());
                bo.setNetSalary(salary.getNetSalary());
                bo.setPaymentStatus("0"); // 未发放
                result.add(bo);
            }

            return result;
        } catch (Exception e) {
            // 记录日志
            log.error("获取待发放薪资列表失败", e);
            return new ArrayList<>();
        }
    }
}
